﻿using System.Collections.Generic;
using System.Linq;
using System.Collections;

namespace Cinemacenter.Shared
{
	public class MarquecineDatabase : SQLiteConnection
	{
		static readonly object locker = new object ();

		public MarquecineDatabase (string path) : base (path)
		{
			CreateTable<Movie> ();
			CreateTable<City> ();
			CreateTable<UpcomingMovie> ();
		}

		public IEnumerable<T> GetItems<T> () where T : IBusinessEntity, new()
		{
			lock (locker) {
				return (Table<T> ().Select (i => i)).ToList ();
			}
		}

		public T GetItem<T> (int id) where T : IBusinessEntity, new()
		{
			lock (locker) {
				return Table<T> ().FirstOrDefault (x => x.ID == id);			
			}
		}

		public int SaveItem<T> (T item) where T : IBusinessEntity
		{
			lock (locker) {
				if (item.ID != 0) {
					Update (item);
					return item.ID;
				}
				return Insert (item);
			}
		}

		public int InsertItems<T> (T items) where T : IEnumerable
		{
			lock (locker) {
				return InsertAll (items);
			}
		}

		public int DeleteItems<T> () where T : IBusinessEntity, new()
		{
			lock (locker) {
				return DeleteAll<T> (new T ());
			}
		}


		public int DeleteItem<T> (int id) where T : IBusinessEntity, new()
		{
			lock (locker) {
				#if NETFX_CORE
				return Delete(new T() { ID = id });
				#else
				return Delete<T> (new T { ID = id });
				#endif
			}
		}
	}
}

